package com.jrapider.manager.service.user;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jrapider.CommonConstants;
import com.jrapider.exception.TransRollbackException;
import com.jrapider.manager.data.om.SysUser;
import com.jrapider.om.JSONResult;
import com.jrapider.utils.MD5;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import lombok.extern.log4j.Log4j2;

import com.jrapider.manager.data.mapper.SysUserMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
@Log4j2
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> {

    @Transactional(rollbackFor = TransRollbackException.class)
    public boolean saveData(SysUser sysUser) {
        if (saveOrUpdate(sysUser)) {
            //如果没设置密码，密码和登录名一样
            baseMapper.initPassword(sysUser.getId(), MD5.encode(sysUser.getLoginId()));
            return true;
        } else {
            return false;
        }
    }

    public SysUser validate(String loginId, String password) {
        if (StringUtils.isEmpty(password)) {
            return null;
        } else {
            return baseMapper.validate(loginId, password);
        }
    }

    public IPage<SysUser> queryUserWithRole(String link, IPage<SysUser> page, String loginId, Long roleId) {
        List<SysUser> list;
        if (CommonConstants.DICT_TRUE.equals(link)) {
            list = baseMapper.queryUserWithRole(page, "%" + loginId + "%", roleId);
            page.setRecords(list);
        } else if (CommonConstants.DICT_FALSE.equals(link)) {
            list = baseMapper.queryUserWithNoRole(page, "%" + loginId + "%", roleId);
            page.setRecords(list);
        } else {
            SysUser condition = new SysUser();
            QueryWrapper<SysUser> qw = new QueryWrapper(condition);
            qw.like("login_id", loginId);
            page = baseMapper.selectPage(page, qw);
            list = page.getRecords();
        }
        for (SysUser sysUser : list) {
            Long count = baseMapper.existRole(sysUser.getId(), roleId);
            if (count > 0) {
                sysUser.setLink(CommonConstants.DICT_TF_TRUE);
            } else {
                sysUser.setLink(CommonConstants.DICT_TF_FALSE);
            }
        }

        return page;
    }


    @Transactional(rollbackFor = TransRollbackException.class)
    public JSONObject linkUser(Long roleId, Long[] userIds, Boolean link) {

        if (link) {
            try {
                baseMapper.insertUserRelation(roleId, userIds);
            } catch (DuplicateKeyException e) {
                throw new TransRollbackException("部分用户已关联,无法继续关联");
            }

        } else {
            for (Long userId : userIds) {
                baseMapper.deleteUserRelation(roleId, userId);
            }
        }
        return JSONResult.newBuilder().success("更新成功").build();
    }

    public int changePwd(String loginId, String oldpwd, String newpwd) {
        return  baseMapper.changePwd(loginId, MD5.encode(oldpwd),MD5.encode(newpwd));
    }
}
